import java.util.ArrayList;
import java.util.Iterator;

public class Crawler {

	private ArrayList<String> listeAttente = new ArrayList<String>();
	private ArrayList<String> knownArtists = new ArrayList<String>();
	
	private Parser parser = new Parser();
	
	private static int count=0;
	private static Object key = new Object();

	public Crawler(String artiste) {
		listeAttente.add(artiste);
		knownArtists.add(artiste);
	}

	public void run() {
		while (listeAttente.size() != 0) {
			String artiste = listeAttente.remove(0);
			this.parser(artiste);
			/*try {
				key.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}*/
		}
	}

	private void parser(String artiste) {
		ArrayList<String> relatedArtists = url2artist(parser.getRelatedArtists(artiste));
		
		for (String artist:relatedArtists) {
			if (!knownArtists.contains(artist)) {
				knownArtists.add(artist);
				listeAttente.add(artist);
			}
		}
		parser.getTopAlbums(artiste);
		parser.getTopTags(artiste);
		System.out.println("artist added ("+count+++") : "+artiste);
		//key.notify();
	}

	private static ArrayList<String> url2artist(ArrayList<String> listeUrl) {
		ArrayList<String> listeArtistes = new ArrayList<String>();
		if (listeUrl != null)
			for (String url : listeUrl) {
				String[] urlSplited = url.split("http://www.last.fm/music/");
				if (urlSplited.length == 2){
					listeArtistes.add(url.split("http://www.last.fm/music/")[1]);
					}
			}
		return listeArtistes;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String artiste = "Metallica";
		if (args.length == 1) {
			artiste = args[0];
		}
		Crawler crawler = new Crawler(artiste);
		crawler.run();
	}

}
